/**
 * 认证相关工具函数
 */

/**
 * 检查用户是否已登录
 * @returns {boolean} 是否已登录
 */
function isLoggedIn() {
  const userInfo = wx.getStorageSync('userInfo');
  const userId = wx.getStorageSync('userId');
  const accessToken = wx.getStorageSync('access_token');
  
  const hasBasicInfo = userInfo && userId;
  const hasToken = accessToken && accessToken.trim() !== '';
  
  console.log('检查登录状态:', {
    hasBasicInfo,
    hasToken,
    userId: userId || 'null',
    tokenLength: accessToken ? accessToken.length : 0
  });
  
  return hasBasicInfo && hasToken;
}

/**
 * 获取当前用户信息
 * @returns {Object|null} 用户信息对象或null
 */
function getCurrentUser() {
  if (!isLoggedIn()) {
    return null;
  }
  
  return {
    userInfo: wx.getStorageSync('userInfo'),
    userId: wx.getStorageSync('userId'),
    openid: wx.getStorageSync('openid'),
    accessToken: wx.getStorageSync('access_token')
  };
}

/**
 * 清除登录信息
 */
function clearLoginInfo() {
  wx.removeStorageSync('access_token');
  wx.removeStorageSync('userInfo');
  wx.removeStorageSync('userId');
  wx.removeStorageSync('openid');
  wx.removeStorageSync('userTitle');
  
  console.log('已清除所有登录信息');
}

/**
 * 跳转到登录页面
 * @param {string} redirectUrl 登录成功后要跳转的页面
 */
function redirectToLogin(redirectUrl = '') {
  const url = redirectUrl ? `/pages/login/login?redirect=${encodeURIComponent(redirectUrl)}` : '/pages/login/login';
  
  // 检查当前页面是否已经是登录页面，避免重复跳转
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage && currentPage.route === 'pages/login/login') {
    console.log('当前已在登录页面，跳过跳转');
    return;
  }
  
  wx.navigateTo({
    url: url,
    fail: (err) => {
      console.error('跳转登录页面失败:', err);
      // 如果navigateTo失败，尝试使用redirectTo
      wx.redirectTo({
        url: url
      });
    }
  });
}

/**
 * 检查并处理认证状态
 * 如果未登录，自动跳转到登录页面
 * @param {string} redirectUrl 登录成功后要跳转的页面
 * @returns {boolean} 是否已登录
 */
function requireAuth(redirectUrl = '') {
  if (isLoggedIn()) {
    return true;
  }
  
  console.log('用户未登录，跳转到登录页面');
  wx.showToast({
    title: '请先登录',
    icon: 'none',
    duration: 1500,
    complete: () => {
      setTimeout(() => {
        redirectToLogin(redirectUrl);
      }, 1500);
    }
  });
  
  return false;
}

module.exports = {
  isLoggedIn,
  getCurrentUser,
  clearLoginInfo,
  redirectToLogin,
  requireAuth
};
